# -*- coding:utf-8 -*-
# @Time: 2020/9/2 13:50
# @Author: liupengfei
# @File: serializers.py

from rest_framework import serializers
from apps.system.serializers import ImagesSerializer
from django.conf import settings

from utils.serializersfield import BooleanCheckCharField, ImageUploadCharField
from .models import Product, ProductParameter


class ProductParameterSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductParameter
        fields = '__all__'


class RelateProductSerialzier(serializers.ModelSerializer):
    '''关联产品列表'''
    key = serializers.SerializerMethodField()
    label = serializers.CharField(source='name')

    def get_key(self, obj):
        return obj.id

    class Meta:
        model = Product
        fields = ('key', 'label')


class ProductSerializers(serializers.ModelSerializer):
    thumbnail_path = serializers.SerializerMethodField()
    thumbnail_arr = ImageUploadCharField(source='thumbnail', read_only=True)
    images = serializers.SerializerMethodField(read_only=True)
    details_images = serializers.SerializerMethodField(read_only=True)
    parameters = serializers.SerializerMethodField(read_only=True)
    is_hot_check = BooleanCheckCharField(source='is_hot', read_only=True)
    is_recommend_check = BooleanCheckCharField(source='is_recommend', read_only=True)

    def get_details_images(self, obj):
        return ImagesSerializer(obj.details_images, many=True).data

    def get_images(self, obj):
        return ImagesSerializer(obj.images, many=True).data

    def get_thumbnail_path(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    def get_parameters(self, obj):
        return ProductParameterSerializer(obj.parameters, many=True).data

    class Meta:
        model = Product
        fields = '__all__'
